<template>
  <div>
    <el-card shadow="never">
      <header-title title="公示广告管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            广告标题: <el-input v-model="searchForm.searchName" placeholder="请输入内容" size="small" style="margin: 0 10px 0 10px;width: 120px;" ></el-input>
            状态:<el-select v-model="searchForm.status" @change="changeStatus" placeholder="请选择" size="small" style="margin: 0 10px 0 10px;width: 120px;">
            <el-option :key="3" label="全部" :value="3"></el-option>
            <el-option :key="2" label="未播" :value="2"></el-option>
            <el-option :key="1" label="在播" :value="1"></el-option>
          </el-select>
            广告类型:<el-select v-model="searchForm.adType" @change="changeAdType" placeholder="请选择" size="small" style="margin: 0 10px 0 10px;width: 145px;">
            <el-option :key="3" label="全部" :value="3"></el-option>
            <el-option :key="2" label="后台分配的广告" :value="2"></el-option>
            <el-option :key="1" label="市场添加的广告" :value="1"></el-option>
          </el-select>
            公示屏类型:<el-select v-model="searchForm.machineType" @change="changeMachineType" placeholder="请选择" size="small" style="margin: 0 10px 0 10px;width: 120px;">
            <el-option :key="3" label="全部" :value="3"></el-option>
            <el-option :key="2" label="市场公示屏" :value="2"></el-option>
            <el-option :key="1" label="商户公示屏" :value="1"></el-option>
          </el-select>
            <el-button @click="search" class="button" size="small" round icon="el-icon-search" style="margin: 10px 0;">查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button @click="add" class="button" size="small" round style="margin: 10px 0;">新增广告</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="advertisingData" v-loading="loading" style="width: 100%">
          <el-table-column prop="advertiserName" label="广告商名称"></el-table-column>
          <el-table-column prop="title" label="广告名称"></el-table-column>
          <el-table-column prop="type" label="广告类型"></el-table-column>
          <el-table-column prop="playTime" label="广告时长(秒)"></el-table-column>
          <el-table-column prop="playUrl" label="播放地址"></el-table-column>
          <el-table-column prop="describe" label="内容描述"></el-table-column>
          <el-table-column prop="startDate" label="开始时间"></el-table-column>
          <el-table-column prop="endDate" label="结束时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-tooltip content="点一下就直接停用了噢" placement="top">
                <el-button @click="editAd(scope.row)" :disabled="scope.row.adResourceId !== 0" type="text" style="color:#3dc2c2;">停用广告</el-button>
              </el-tooltip>
              <el-tooltip content="点一下就直接删除了噢" placement="top">
                <el-button @click="deleteAd(scope.row)" :disabled="scope.row.adResourceId !== 0" type="text" style="color:#f7674a;">删除广告</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <div slot="empty"><img src="../../../assets/blank_tip_page/blank_tip_page.png" alt=""></div>
        </el-table>
        <el-pagination
          :page-size="searchForm.perPage"
          :current-page="searchForm.page"
          :total="searchForm.total"
          @current-change="changeAdPage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog title="新增广告" :visible.sync="advertisingDialog" @close="close" v-if="advertisingDialog">
      <div>
        <el-form :model="modal" label-width="100px" :rules="rules" ref="modal">
          <el-form-item label="标题" prop="title">
            <el-input v-model="modal.title"></el-input>
          </el-form-item>
          <el-form-item label="广告类型" prop="type">
            <el-select v-model="modal.type" @change="addChangeType" placeholder="请选择">
              <el-option :key="1" label="图片" :value="1"></el-option>
              <el-option :key="2" label="视频" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告时长(秒)" prop="type">
            <el-select v-model="modal.playTime" @change="addChangePlayTime" placeholder="请选择">
              <el-option :key="15" label="15秒" :value="15"></el-option>
              <el-option :key="30" label="30秒" :value="30"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="播放地址" prop="playUrl">
            <el-row>
              <el-col :span="5">
                <el-upload
                  class="avatar-uploader" ref="playUrl" style="display: inline-block;"
                  action="https://upload.qiniup.com"
                  :on-remove='handleRemove'
                  :on-success="handleSuccessplayUrl"
                  :show-file-list="false"
                  :limit='1'
                  :data='uploadToken'
                  :before-upload="beforeUpload"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-col>
              <el-col :span="19">
                <el-input v-model="modal.playUrl" size="medium"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="内容描述" prop="describe">
            <el-input v-model="modal.describe"></el-input>
          </el-form-item>
          <el-form-item label="公示屏类型" prop="machineType">
            <el-select v-model="modal.machineType" @change="addChangeMachineType" placeholder="请选择">
              <el-option :key="0" label="商户公示屏" :value="0"></el-option>
              <el-option :key="1" label="市场公示屏" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告开始日期" prop="startDate">
            <!-- <el-input v-model="modal.startDate"></el-input> -->
            <el-date-picker
              v-model="modal.startDate"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="广告结束日期" prop="endDate">
            <!-- <el-input v-model="modal.endDate"></el-input> -->
            <el-date-picker
              v-model="modal.endDate"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('modal')">提交新增广告</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle"
import { formatDate3 } from '@/utils'
export default {
  name: 'PublicAdvertising',
  components: {
     HeaderTitle
  },
  data(){
    return {
      searchForm: {
        searchName: '', //	string	false	广告标题或广告描述
        status: 3, //	int	false	状态	1:在播，2：未播，3：全部
        adType: 1, //	int	false	广告类型	1：市场添加的广告，2：后台分配的广告，3：全部，默认值1
        machineType: 3, //	int	false	公示屏类型	1:商户公示屏，2：市场公示屏，3：全部，默认值1
        perPage: 10, // 每页显示10条
        page: 1, // 当前页
        total: 0,
      },
      loading: true,
      advertisingData: [],
      advertisingDialog: false,
      modal: {
        type: 1, //	int	false	广告类型	1:图片，2：视频
        title: '', //	string	true	广告名称
        playTime: 15, //	int	false	广告市场	15或30
        playUrl: '', //	string	true	播放地址
        describe: '', //	string	true	内容描述
        machineType: 1, //	int	false	公示屏类型	0:商户公示屏,1:市场公示屏,默认0
        startDate: formatDate3(new Date(), "yyyy-MM-dd hh:mm:ss"), //	string	true	广告开始日期	年-月-日 时:分:秒
        endDate: formatDate3(new Date(), "yyyy-MM-dd hh:mm:ss"), //	string	true	广告结束日期	年-月-日 时:分:秒
      },
      uploadToken:{
        key: '',
        token: ''
      },
      rules:{
        title:[{
          required:true,message:'请输入标题',trigger:"change"
        }],
        playUrl:[{
          required:true,message:'请上传广告',trigger:"change"
        }],
        describe:[{
          required:true,message:'请输入内容描述',trigger:"change"
        }],
      }
    }
  },
  watch: {
    '$store.state.app.marketId'(val, oldVal){
      this.getAdList(this.searchForm)
      this.goodsToken()
    }
  },
  mounted(){
    this.getAdList(this.searchForm)
    this.goodsToken()
  },
  methods:{
    beforeUpload(file){
      const isPNG = file.type === "image/png"
      const isJPEG = file.type === "image/jpeg"
      const isJPG = file.type === "image/jpg"
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!")
        return false
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
        return false
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date()
      this.uploadToken.key=`bill${date.getFullYear()}${date.getMonth()+1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(Math.random()*100)}.${file.type.split('/')[1]}`
    },
    //获取上传文件时候的token
    goodsToken(){
      this.$store.dispatch('purchaseInfo/uptoken',{}).then(
        data => {
          this.uploadToken.token = data.data.uptoken
        }
      ).catch(err => {
      })
    },
    handleRemove(file, fileList) {
      console.log(file,fileList[0])
    },
    handleSuccessplayUrl(res, file, fileList){
      this.modal.playUrl = 'http://cailanzi.image.cailanzi001.com/' + res.key
      this.$refs.playUrl.clearFiles()
    },
    // 改变广告状态
    changeStatus(val){
      this.searchForm.status = val
    },
    // 改变广告类型
    changeAdType(val){
      this.searchForm.adType = val
    },
    // 改变公示屏类型
    changeMachineType(val){
      this.searchForm.machineType = val
    },
    // 获取广告列表
    getAdList(searchForm){
      this.$store.dispatch('publicScreenInfo/fetchAdData',searchForm).then(
        data => {
          this.loading = false
          for(let i = 0; i < data.items.length; i++){
            if(data.items[i].type === 1){
              data.items[i].type = '图片'
            }else if(data.items[i].type === 2){
              data.items[i].type = '视频'
            }
          }
          this.advertisingData = data.items
          this.searchForm.total = data.total
        }
      ).catch(err => {
        this.loading = false
        this.advertisingData = []
        this.searchForm.total = 0
      })
    },
    search(){
      this.searchForm.page = 1
      this.getAdList(this.searchForm)
    },
    changeAdPage(num){
      this.searchForm.page = num
      this.getAdList(this.searchForm)
    },
    // 点击新增广告
    add(){
      this.advertisingDialog = true
    },
    // 新增 广告类型
    addChangeType(val){
      this.modal.type = val
    },
    // 新增 广告时长
    addChangePlayTime(val){
      this.modal.playTime = val
    },
    // 新增 公示屏类型
    addChangeMachineType(val){
      this.modal.machineType = val
    },
    close(){
      this.clear()
    },
    // 提交新增广告
    submit(formName){
       this.$refs[formName].validate(valid => {
        if (valid) {
      console.log('提交新增广告')
      console.log(this.modal)
      this.advertisingDialog = false
      this.$store.dispatch("publicScreenInfo/submitAdversing", this.modal).then(data=>{
        if(data){
          this.$message({
            type: 'success',
            message: '操作成功，请刷新！'
          })
        }
        this.getAdList(this.searchForm)
        this.clear()
      }).catch(err => {
        this.clear()
      })
       } else {
          this.$message.error("必填项未填");
          return false;
        }
      });
    },
    clear(){
      this.modal = {
        type: 1, //	int	false	广告类型	1:图片，2：视频
        title: '', //	string	true	广告名称
        playTime: 15, //	int	false	广告市场	15或30
        playUrl: '', //	string	true	播放地址
        describe: '', //	string	true	内容描述
        machineType: 1, //	int	false	公示屏类型	0:商户公示屏,1:市场公示屏,默认0
        startDate: formatDate3(new Date(), "yyyy-MM-dd hh:mm:ss"), //	string	true	广告开始日期	年-月-日 时:分:秒
        endDate: formatDate3(new Date(), "yyyy-MM-dd hh:mm:ss"), //	string	true	广告结束日期	年-月-日 时:分:秒
      }
    },
    // 点击停用广告
    editAd(row){
      const id = row.id
      this.$store.dispatch("publicScreenInfo/editAd", {id}).then(data=>{
        if(data){
          this.$message({
            type: 'success',
            message: '操作成功，请刷新！'
          })
        }
        this.getAdList(this.searchForm)
      }).catch(err => {
      })
    },
    // 删除广告
    deleteAd(row){
      const id = row.id
      this.$store.dispatch("publicScreenInfo/deleteAd", {id}).then(data=>{
        if(data){
          this.$message({
            type: 'success',
            message: '操作成功，请刷新！'
          })
        }
        this.getAdList(this.searchForm)
      }).catch(err => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  /deep/ .el-table__empty-text{
    width: 100%;
  }
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
</style>
